package com.cycle.community.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cycle.community.constant.CommunityConstant;
import com.cycle.community.constant.LoginTicketConstant;
import com.cycle.community.constant.UserConstant;
import com.cycle.community.dao.LoginTicketMapper;
import com.cycle.community.dao.UserMapper;
import com.cycle.community.entity.LoginTicket;
import com.cycle.community.entity.User;
import com.cycle.community.util.CommunityUtil;
import com.cycle.community.util.MailClient;
import com.cycle.community.util.RedisKeyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author lenovo
 * @create 2022/8/11 19:36
 */
@Service
public class UserService implements CommunityConstant {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MailClient mailClient;

    @Autowired
    private TemplateEngine templateEngine;

    //    @Autowired
//    private LoginTicketMapper loginTicketMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    public User findUserById(long id) {
//        return userMapper.selectById(id);
        //重构
        User user = getCache(id);
        if (user == null) {
            user = initCache(id);
        }
        return user;
    }

    /**
     * @param user
     * @return map map为空表示没有问题
     */
    public Map<String, Object> register(User user) {
        Map<String, Object> map = new HashMap<>();
        //空值处理，空值直接抛异常
        if (user == null) {
            throw new IllegalArgumentException("参数不能为空");
        }
        if (StringUtils.isBlank(user.getUsername())) {
            //业务漏洞
            map.put("usernameMsg", "账号不能为空");
            return map;
        }
        if (StringUtils.isBlank(user.getPassword())) {
            //业务漏洞
            map.put("passwordMsg", "密码不能为空");
            return map;
        }
        if (StringUtils.isBlank(user.getEmail())) {
            map.put("emailMsg", "邮箱不能为空");
            return map;
        }
        //验证账号
        User u = userMapper.selectByName(user.getUsername());
        if (u != null) {
            map.put("usernameMsg", "该账号已存在!");
            return map;
        }
        //验证邮箱
        u = userMapper.selectByEmail(user.getEmail());
        if (u != null) {
            map.put("emailMsg", "该邮箱已被注册!");
            return map;
        }

        //注册用户
        user.setSalt(CommunityUtil.generateUUID().substring(0, 5));//5位
        user.setPassword(CommunityUtil.md5(user.getPassword() + user.getSalt()));
        user.setType(UserConstant.ORDINARY_USER);
        user.setStatus(UserConstant.NOT_ACTIVE);
        user.setActivationCode(CommunityUtil.generateUUID());
        user.setHeaderUrl(String.format("https://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));
        user.setCreateTime(new Date());
        userMapper.insert(user);

        //激活邮件 org.thymeleaf.context.Context;
        Context context = new Context();
        context.setVariable("email", user.getEmail());
        //http://localhost:8080/community/activation/101/code
        //insert之后就有id，mybatis回填
        String url = domain + contextPath + "/activation/" + user.getId() + "/" + user.getActivationCode();
        context.setVariable("url", url);
        String content = templateEngine.process("/mail/activation", context);
        mailClient.sendMail(user.getEmail(), "激活账号", content);

        return map;
    }

    public int activation(long userId, String code) {
        User user = userMapper.selectById(userId);
        if (user.getStatus() == 1) {//重复激活
            return ACTIVATION_REPEAT;
        } else if (user.getActivationCode().equals(code)) {
//            UpdateWrapper<User> wrapper = new UpdateWrapper<>();
//            //设置为重复
//            wrapper.lambda().set(equals(user), User::getStatus, ACTIVATION_REPEAT);
//            userMapper.updateById(user, wrapper);//全部更新
            user.setStatus(ACTIVATION_REPEAT);
            userMapper.updateById(user);
            //激活是修改user，清除缓存
            clearCache(userId);
            return ACTIVATION_SUCCESS;
        } else {
            return ACTIVATION_FAILURE;
        }
    }

    /**
     * 登录
     *
     * @param username
     * @param password
     * @param expiredSeconds 过期时间
     * @return
     */
    public Map<String, Object> login(String username, String password, int expiredSeconds) {
        Map<String, Object> map = new HashMap<>();
        //空值处理
        if (StringUtils.isBlank(username)) {
            map.put("usernameMsg", "账号不能为空！");
            return map;
        }
        if (StringUtils.isBlank(password)) {
            map.put("passwordMsg", "密码不能为空！");
            return map;
        }
        //验证账号
        User user = userMapper.selectByName(username);
        if (user == null) {
            map.put("usernameMsg", "该账号不存在！");
            return map;
        }
        //判断是否激活
        if (user.getStatus() == UserConstant.NOT_ACTIVE) {
            map.put("usernameMsg", "该账号未激活！");
            return map;
        }
        //验证密码
        password = CommunityUtil.md5(password + user.getSalt());
        if (!user.getPassword().equals(password)) {
            map.put("passwordMsg", "密码不正确！");
            return map;
        }
        //生成登录凭证
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setUserId(user.getId());
        loginTicket.setTicket(CommunityUtil.generateUUID());
        loginTicket.setExpired(new Date(System.currentTimeMillis() + expiredSeconds * 1000));
//        loginTicketMapper.insert(loginTicket);
        //重构
        String redisKey = RedisKeyUtil.getTicketKey(loginTicket.getTicket());
        //每个人单独存一份就行了，直接序列化
        //redisTemplate会自动将value的对象序列化为json字符串并保存
        redisTemplate.opsForValue().set(redisKey, loginTicket);

        //凭证发到客户端
        map.put("ticket", loginTicket.getTicket());
        return map;
    }

    public void logout(String ticket) {
//        loginTicketMapper.updateStatus(ticket, LoginTicketConstant.INVALID);
        //重构
        String redisKey = RedisKeyUtil.getTicketKey(ticket);
        LoginTicket loginTicket = (LoginTicket) redisTemplate.opsForValue().get(redisKey);
        loginTicket.setStatus(LoginTicketConstant.INVALID);
        redisTemplate.opsForValue().set(redisKey, loginTicket);
    }

    public LoginTicket findLoginTicket(String ticket) {
//        return loginTicketMapper.selectByTicket(ticket);
        //重构
        String redisKey = RedisKeyUtil.getTicketKey(ticket);
        return (LoginTicket) redisTemplate.opsForValue().get(redisKey);

    }

    public int updateHeader(long userId, String headerUrl) {
        //清除缓存
//        //两个没办法事务，事务是分开的，万一更新失败，缓存缺清理掉了
//        clearCache(userId);
//        return userMapper.updateHeader(userId, headerUrl);
        int rows = userMapper.updateHeader(userId, headerUrl);
        clearCache(userId);//更新之后再清理
        return rows;
    }

    public User findUserByName(String username) {
        return userMapper.selectByName(username);
    }


    //1,优先从缓存中取值
    private User getCache(long userId) {
        String redisKey = RedisKeyUtil.getUserKey(userId);
        return (User) redisTemplate.opsForValue().get(redisKey);
    }

    //2.取不到时初始化缓存数据
    private User initCache(long userId) {
        User user = userMapper.selectById(userId);
        String redisKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.opsForValue().set(redisKey, user, 3600, TimeUnit.SECONDS);//一个小时过期
        return user;
    }

    //3.数据变更时请求缓存数据
    private void clearCache(long userId) {
        String redisKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.delete(redisKey);
    }

    //获得用户权限
    public Collection<? extends GrantedAuthority> getAuthorities(long userId) {
        //根据userId查user
        User user = this.findUserById(userId);
        List<GrantedAuthority> list = new ArrayList<>();
        list.add(new GrantedAuthority() {
            @Override
            public String getAuthority() {
                switch (user.getType()) {
                    case UserConstant.SUPER_ADMINISTRATOR:
                        return AUTHORITY_ADMIN;
                    case UserConstant.MODERATOR:
                        return AUTHORITY_MODERATOR;
                    default:
                        return AUTHORITY_USER;
                }
            }
        });
        return list;
    }
}
